import requests
from selenium import webdriver
import time, re, utils, random, json
from  wx_login import WechatLogin
from urllib3.exceptions import InsecureRequestWarning

requests.urllib3.disable_warnings(InsecureRequestWarning)


# 自动化扫码
class Scan:

    def __init__(self, session, gh_id, gh_nickname, url='https://mp.weixin.qq.com'):
        self.url = url
        self.gh_id = gh_id
        self.nickname = gh_nickname
        self.session = session
        self.driver = webdriver.Chrome('C:\\chromedriver\\chromedriver.exe')

    # 保存数据
    def save_data(self, data_file, data_date, data):
        with utils.open_write_data_file(self.gh_id, data_file, data_date) as f:
            json.dump(data, f)

    def get_session_with_cookie(self, gh_id, pwd, nickname):
        data = utils.get_post_data(gh_id, pwd)
        res = self.session.post(self.url + '/cgi-bin/bizlogin?action=startlogin', data=data, headers=utils.headers,
                                verify=False)
        c = requests.utils.dict_from_cookiejar(res.cookies)
        self.driver.maximize_window()
        self.driver.get(self.url + res.json()['redirect_url'])

        for key in c:
            self.driver.add_cookie({'name': key,  'value': c[key]})
            self.session.cookies.set(key, c[key])

        self.driver.get('https://mp.weixin.qq.com' + res.json()['redirect_url'])
        date = self.session.get('https://mp.weixin.qq.com' + res.json()['redirect_url'], verify=False)
        if "帐号迁移审核及发票" in date.text:
            wlogin = WechatLogin(gh_id, pwd)
            re_url, session = wlogin.get_session_with_cookie()
            resp = session.get('{0}&f=json&ajax=1&random={1}'.format(re_url, random.random()), verify=False)
            try:
                res = resp.json()
                if (res['base_resp']['err_msg'] == 'ok'):
                    if 'acct_transfer' in res:
                        transfer_status = utils.get_transfer_status(res['acct_transfer']['transfer_status']) # 迁移状态
                        info = {"gh_id": gh_id,
                                "nickname": nickname}
                        self.save_data('transfer.json', utils.get_yesterday(), transfer_status)
                        self.save_data('basic.json', utils.get_yesterday(), dict(info))
                        self.save_data('basic.json', utils.get_today(), dict(info))
                        self.driver.quit()
            except:
                print(gh_id)
            return
        token = []
        while 1:
            current_url = self.driver.current_url
            if re.search('token', current_url):
                token.append(re.search('token=(.*)', current_url).group(1))
                break

        for cookie in self.driver.get_cookies():
            self.session.cookies.set(cookie['name'], cookie['value'])

        self.driver.quit()
        return token[0]
